package com.wasion.pwportable.jsi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.wasion.core.db.Pagination;
import com.wasion.core.db.storage.SqliteStorage;
import com.wasion.core.db.storage.SqliteStorageListener.DataInsertListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataQueryListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataUpdateListener;
import com.wasion.core.db.storage.StorageQuery;
import com.wasion.core.db.storage.StorageQuery.SortOrder;
import com.wasion.core.util.DateTimeUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.dao.sd.SchemeSDDBDao;
import com.wasion.pwportable.dao.sd.TerminalSDDBDao;
import com.wasion.pwportable.dao.sd.WorkLineSDDBDao;
import com.wasion.pwportable.domain.po.Scheme;
import com.wasion.pwportable.domain.po.Terminal;
import com.wasion.pwportable.domain.po.WorkLine;

/**
 * 
 * @ClassName: SchemeJSI
 * @Description: 方案JavaScriptInterface，对方案操作交互接口<br/>
 *               1. 增加/修改方案 <br/>
 *               2. 删除方案 <br/>
 *               3. 获取方案 <br/>
 *               4. 查詢施工方案树（方案-线路-终端）</br>
 * @author 高意
 * @date 2014-8-1 下午2:57:06
 * 
 */
public class SchemeJSI {

	// 应用上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Sqlite存储实例
	private SqliteStorage sqliteStorage = null;

	// Google的Json转换工具
	private Gson gson = new Gson();

	// 是否点击查询按钮触发事件
	private boolean isQuery;

	// 方案数据库访问接口
	private SchemeSDDBDao schemeSDDBDao = null;

	Scheme scheme = new Scheme();

	public SchemeJSI(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
		this.sqliteStorage = SqliteStorage.getInstance(this.context);
		schemeSDDBDao = new SchemeSDDBDao(context);
	}

	/**
	 * 
	 * @Title: initData
	 * @Description: 初始化方案表
	 * @param
	 * @return
	 * @throws
	 */
	public void initData() {

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("_id", 1);

		sqliteStorage.findData(storageQuery, schemeSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "初始化方案失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null == paramList || 0 == paramList.size()) { // 不存在id为1的记录，则插入
							Scheme scheme = new Scheme();
							scheme.setSchemename("默认方案");
							scheme.setTime(DateTimeUtil.getCurrentDate());

							sqliteStorage.insertData(scheme, schemeSDDBDao,
									new DataInsertListener() {

										public void onSuccess(long paramLong) {
										}

										public void onFailure(int errorCode,
												String errorMessage) {
										}
									});
						}
					}
				});
	}

	/**
	 * 
	 * @Title: addOrModifyScheme
	 * @Description: 新增/修改方案
	 * @param
	 * @return
	 * @throws
	 */
	public void addOrModifyScheme(final String jsonStr) {

		scheme = gson.fromJson(jsonStr, Scheme.class);
		scheme.setTime(DateTimeUtil.getCurrentDate());

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("schemename", scheme.getSchemename());
		if (0 == scheme.get_id()) { // 为0，新增

			sqliteStorage.findData(storageQuery, schemeSDDBDao,
					new DataQueryListener() {

						public void onFailure(int errorCode, String errorMessage) {
							JSIHelper.showToast(context, "添加失败!");
						}

						public void onSuccess(List<?> paramList) {

							if (null != paramList && 0 < paramList.size()) {
								JSIHelper
										.showToast(context, "方案名称已存在, 不能重复添加!");
								return;
							}

							sqliteStorage.insertData(scheme, schemeSDDBDao,
									new DataInsertListener() {

										public void onSuccess(long paramLong) {

											if (0 == paramLong) {
												JSIHelper.showToast(context,
														"添加失败!");
												return;
											}

											JSIHelper.showToast(context,
													"添加成功!");
											Map<String, Object> map = new HashMap<String, Object>();
											map.put("type", "scheme");

											String result = gson.toJson(map);
											webView.loadUrl("javascript:editSuccessCallback("
													+ result + ")");
										}

										public void onFailure(int errorCode,
												String errorMessage) {
											JSIHelper.showToast(context,
													"添加失败!");
										}
									});
						}
					});

		} else { // 修改
			storageQuery.notEqual("_id", scheme.get_id());
			sqliteStorage.findData(storageQuery, schemeSDDBDao,
					new DataQueryListener() {

						public void onFailure(int errorCode, String errorMessage) {
							JSIHelper.showToast(context, "修改失败!");
						}

						public void onSuccess(List<?> paramList) {

							if (null != paramList && 0 < paramList.size()) {
								JSIHelper
										.showToast(context, "方案名称已存在, 不能重复添加!");
								return;
							}

							sqliteStorage.updateData(scheme, schemeSDDBDao,
									new DataUpdateListener() {

										public void onSuccess(long paramLong) {

											if (0 == paramLong) {
												JSIHelper.showToast(context,
														"修改失败!");
												return;
											}

											JSIHelper.showToast(context,
													"修改成功!");
											Map<String, Object> map = new HashMap<String, Object>();
											map.put("type", "scheme");

											String result = gson.toJson(map);
											webView.loadUrl("javascript:editSuccessCallback("
													+ result + ")");
										}

										public void onFailure(int errorCode,
												String errorMessage) {
											JSIHelper.showToast(context,
													"修改失败!");
										}
									});
						}
					});

		}
	}

	/**
	 * 
	 * @Title: removeScheme
	 * @Description: 删除方案
	 * @param
	 * @return
	 * @throws
	 */
	public void removeScheme(final String _id) {

		if (StringUtil.isEmpty(_id)) {
			JSIHelper.showToast(context, "方案唯一标识不能为空!");
			return;
		}

		StorageQuery storageQuery = new StorageQuery();
		storageQuery.equals("schemeid", _id);

		sqliteStorage.findData(storageQuery, new WorkLineSDDBDao(context),
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "删除方案失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							JSIHelper.showToast(context, "方案下存在线路, 不能删除!");
							webView.loadUrl("javascript:removePauseCallback()");
							return;
						}

						StorageQuery sq = new StorageQuery();
						sq.equals("_id", Integer.parseInt(_id));

						sqliteStorage.deleteData(sq, schemeSDDBDao,
								new DataUpdateListener() {

									public void onSuccess(long paramLong) {
										JSIHelper.showToast(context, "删除成功!");
										webView.loadUrl("javascript:removeSuccuessCallback()");
									}

									public void onFailure(int errorCode,
											String errorMessage) {
										JSIHelper.showToast(context, "删除失败!");
									}
								});
					}
				});

	}

	/**
	 * 
	 * @Title: querySchemes
	 * @Description: 获取方案
	 * @param
	 * @return
	 * @throws
	 */
	public void querySchemes(final String jsonStr) {

		// Scheme scheme = new Scheme();
		scheme = gson.fromJson(jsonStr, Scheme.class);

		StorageQuery storageQuery = new StorageQuery();

		if (null != scheme) {
			int _id = scheme.get_id();
			if (0 != _id) {
				storageQuery.equals("_id", _id);
			}
		}

		sqliteStorage.findData(storageQuery, schemeSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询方案失败!");
					}

					public void onSuccess(List<?> paramList) {

						if (null != paramList && 0 < paramList.size()) {
							try {
								Map<String, Object> map = new HashMap<String, Object>();
								if (null != scheme) {
									map.put("flag", "modify");
								} else {
									map.put("flag", "query");
								}
								map.put("list", paramList);
								String result = gson.toJson(map);
								// String jsonStr = gson.toJson(paramList);

								webView.loadUrl("javascript:loadSchemes("
										+ result + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						}
					}
				});
	}

	/**
	 * 
	 * @Title: querySchemesByPage
	 * @Description: 分页获取方案
	 * @param
	 * @return
	 * @throws
	 */
	public void querySchemesByPage(final String jsonStr) {

		StorageQuery storageQuery = new StorageQuery();
		try {
			JSONObject jsObj = new JSONObject(jsonStr);

			isQuery = jsObj.getBoolean("isQuery");
			if (!jsObj.isNull("schemename")) {
				storageQuery.like("schemename", jsObj.getString("schemename"));
			}

			int size = Pagination.DEFAULT_PAGE_SIZE;
			if (!jsObj.isNull("pagesize")) {
				storageQuery.setLimit(Integer.parseInt(jsObj
						.getString("pagesize")));
			} else {
				storageQuery.setLimit(Pagination.DEFAULT_PAGE_SIZE);
			}

			if (!jsObj.isNull("page")) {
				storageQuery.setOffset(size
						* (Integer.parseInt(jsObj.getString("page")) - 1));
			} else {
				storageQuery.setOffset(size * (Pagination.DEFAULT_PAGE - 1));
			}

			storageQuery.addSort("time", SortOrder.DESC);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		sqliteStorage.findData(storageQuery, schemeSDDBDao,
				new DataQueryListener() {

					public void onFailure(int errorCode, String errorMessage) {
						JSIHelper.showToast(context, "查询方案失败!");
					}

					public void onSuccess(List<?> paramList) {

						String jsonStr = gson.toJson(paramList);
						if (isQuery
								|| (null != paramList && 0 < paramList.size())) {
							try {
								webView.loadUrl("javascript:querySchemesByPageCallback("
										+ jsonStr + ")");
							} catch (Exception e) {
								JSIHelper.showToast(context, e.getMessage());
							}
						} else {
							JSIHelper.showToast(context, "已加载所有方案!");
						}
					}
				});
	}

	/**
	 * 
	 * @Title: querySchemeTreeNodes
	 * @Description: 查询实施方案的所有节点
	 * @param
	 * @return
	 * @throws
	 */
	public void querySchemeTreeNodes() {

		PwPortableActivity.getHandler().post(new Runnable() {
			public void run() {
				try {
					schemeSDDBDao.startReadableDatabase(false);
					List<Scheme> schemes = schemeSDDBDao.queryList(
							new String[] { "_id", "schemename" }, null, null,
							null, null, "time desc", null);
					schemeSDDBDao.closeDatabase(false);

					for (Scheme s : schemes) {
						WorkLineSDDBDao workLineSDDBDao = new WorkLineSDDBDao(
								context);
						workLineSDDBDao.startReadableDatabase(false);
						List<WorkLine> workLines = workLineSDDBDao.queryList(
								new String[] { "_id", "linename", "schemeid" },
								"schemeid=?", new String[] { s.get_id() + "" },
								null, null, "time desc", null);
						workLineSDDBDao.closeDatabase(false);

						s.setWorkLines(workLines);

						for (WorkLine w : workLines) {
							TerminalSDDBDao terminalSDDBDao = new TerminalSDDBDao(
									context);
							terminalSDDBDao.startReadableDatabase(false);
							List<Terminal> terminals = terminalSDDBDao
									.queryList(new String[] { "_id",
											"terminaladdr", "wirelessaddr" },
											"lineid=?",
											new String[] { w.get_id() + "" },
											null, null, "time desc", null);
							terminalSDDBDao.closeDatabase(false);

							w.setTerminals(terminals);
						}
					}

					String jsonStr = gson.toJson(schemes);

					webView.loadUrl("javascript:loadSTreeCallback(" + jsonStr
							+ ")");
				} catch (Exception e) {
					JSIHelper.showToast(context, "加载实施方案列表异常!");
				}
			}
		});
	}
}
